package de.szut.internalorganizer;

import java.io.FileWriter;
import java.io.IOException;

/**
 * Class for saving sudokufields
 * 
 * @author dqi12huisinga
 * 
 */
public class InternalSaver extends InternalOrganizer {
	private boolean restrictAccessToFile;

	public InternalSaver() {
		setRestrictAccessToFile(false);
	}

	public boolean isFileAccessRestricted() {
		return restrictAccessToFile;
	}

	public void setRestrictAccessToFile(boolean restrictFile) {
		this.restrictAccessToFile = restrictFile;
	}

	/**
	 * Method for saving the data
	 * 
	 * @param fileName
	 * @param identifier
	 * @param field1
	 * @param field2
	 * @param field3
	 * @throws IOException
	 */
	public void saveData(String fileName, String identifier, String[][] field1,
			String[][] field2, String[][] field3) throws IOException {
		String lineSeparator = System.getProperty("line.separator");

		// Unlocks the file if necessary
		getFile().setReadable(true);
		getFile().setWritable(true);
		// Creates a new file if the respective file doesn't exist yet
		getFile().createNewFile();
		FileWriter fileWriter = new FileWriter(getFile());
		// Writes an identifier
		fileWriter.write(identifier + lineSeparator);
		// Writes data
		for (String[] currentLine : field1) {
			for (String currentDate : currentLine) {
				fileWriter.write(currentDate);
				fileWriter.write(getDataSeparator());
			}
			fileWriter.write(lineSeparator);
		}
		fileWriter.write(lineSeparator);
		// Writes data
		for (String[] currentLine : field2) {
			for (String currentDate : currentLine) {
				fileWriter.write(currentDate);
				fileWriter.write(getDataSeparator());
			}
			fileWriter.write(lineSeparator);
		}
		fileWriter.write(lineSeparator);
		// Writes data
		for (String[] currentLine : field3) {
			for (String currentDate : currentLine) {
				fileWriter.write(currentDate);
				fileWriter.write(getDataSeparator());
			}
			fileWriter.write(lineSeparator);
		}
		// Closes the FileWriter
		fileWriter.close();

		// Sets restricted access if necessary
		if (restrictAccessToFile) {
			getFile().setReadable(false);
			getFile().setWritable(false);
		}
	}
}
